package com.limi.akka.scheduler;

import akka.actor.AbstractActorWithTimers;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import org.junit.Test;

import java.time.Duration;

/**
 * @author Limi Pan
 * @create 2018-09-17 15:40
 */
public class TimerTest{

    static class SchedulerActor extends AbstractActorWithTimers {

        private static Object TICK_KEY = "TickKey";
        int count = 0;

        public SchedulerActor() {
            // getTimers().startSingleTimer(TICK_KEY, new Tick(), Duration.ofSeconds(1));
        }

        public static Props props(){
            return Props.create(SchedulerActor.class, () -> new SchedulerActor());
        }
        public static final class FirstTick{
        }
        private static final class Tick{
        }

        @Override
        public Receive createReceive() {
            return receiveBuilder()
                    .match(FirstTick.class, message -> {
                        System.out.println("do FirstTick... " + SchedulerTest.getNowTime());
                        Tick tick = new Tick();
                        getTimers().startPeriodicTimer(TICK_KEY, tick, Duration.ofSeconds(1));
                    })
                    .match(Tick.class, message -> {
                        System.out.println(getSender().path().name()+" do Tick... 第" + count + "次 " + SchedulerTest.getNowTime());
                        count++;
                    })
                    .build();
        }

    }

    @Test
    public void test() throws InterruptedException {
        ActorSystem system = ActorSystem.create("Iot");
        ActorRef ref = system.actorOf(SchedulerActor.props());

        System.out.println("test start... " + SchedulerTest.getNowTime());
        ref.tell(new SchedulerActor.FirstTick(), ActorRef.noSender());
        Thread.sleep(10000);

    }

}
